﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//MicroDesigner
using Jc.MicroDesigner.Objects;
using Jc.MicroDesigner.Management;

namespace Jc.MicroDesigner.ToolWindows
{
    /// <summary>
    /// Форма запуска схем на выполнение
    /// Содержит вкладку настроек и вкладку результатов
    /// </summary>
    public partial class StartItForm : Form
    {
        private DateTime _Time = DateTime.Now;
        private ObjectManager _Manager = null;

        /// <summary>
        /// Создать форму запуска
        /// </summary>
        public StartItForm()
        {
            InitializeComponent();
            TimeScroll.Scroll += new ScrollEventHandler(TimeScroll_Scroll);
            this.SizeChanged += new EventHandler(SignalsViewer_Resize);
            OptionsGrid.SelectedObject = StartOptions.Options;
        }

        /// <summary>
        /// Перерисовать диаграмму
        /// </summary>
        public void RefreshDiagram()
        {
            SignalsViewPanel.ViewRange(TimeScroll.Value, ListScrollbar.Value);
        }

        /// <summary>
        /// Вызвать форму для текущей схемы
        /// </summary>
        /// <param name="manager">Логическая схема</param>
        public void Show(ObjectManager manager)
        {
            _Manager = manager;

            StartOptions.Options.StartSignal = _Manager.InitialSignal;
            StartOptions.Options.TactCount = Convert.ToUInt16(_Manager.TactCount);
            StartOptions.Options.TactTime = Convert.ToUInt16(_Manager.TicPerTact);

            _Manager.OnEmulateComplete += new onProcessComplete(_Manager_OnEmulateComplete);
            StartOptions.Options.Manager = manager;
            ShowDialog();
        }

        /// <summary>
        /// Запустить построение диаграммы
        /// </summary>
        /// <param name="data">Данные запуска</param>
        public void GenerateDiagram(List<SignalContainer> data)
        {
            int max = _Manager.TicPerTact * _Manager.TactCount;
            TimeScroll.Maximum = max;
            ListScrollbar.Maximum = data.Count;
            SignalsViewPanel.GenerateDiagram(data);
        }

        #region Events

        void _Manager_OnEmulateComplete()
        {
            StartPages.SelectedIndex = 1;
            GenerateDiagram(_Manager.Watches);
            TimeLabel.Text = "Время запуска: " + (DateTime.Now - _Time).ToString();
            OptionsGroup.Enabled = true;
        }

        void TimeScroll_Scroll(object sender, ScrollEventArgs e)
        {
            if (e.Type == ScrollEventType.EndScroll)
                RefreshDiagram();
        }

        void RefreshBtn_Click(object sender, EventArgs e)
        {
            SignalsViewPanel.SignalWidth = Convert.ToInt32(SignalScaleWidth.Value);
            SignalsViewPanel.TimeInterval = Convert.ToInt32(TimeSpanBox.Value);
            SignalsViewPanel.TimeTableVisible = TimeTableCheckBox.Checked;
            SignalsViewPanel.TimeTagsVisible = TimeTagsCheckBox.Checked;
            RefreshDiagram();
        }

        void SignalsViewer_Resize(object sender, EventArgs e)
        {
            RefreshDiagram();
        }

        void ListScrollbar_Scroll(object sender, ScrollEventArgs e)
        {
            if (e.Type == ScrollEventType.EndScroll)
                RefreshDiagram();
        }

        private void StartBtn_Click(object sender, EventArgs e)
        {
            _Time = DateTime.Now;
            _Manager.TactCount = StartOptions.Options.TactCount;
            _Manager.TicPerTact = StartOptions.Options.TactTime;
            _Manager.InitialSignal = StartOptions.Options.StartSignal;
            //настроить панель вывода
            SignalsViewPanel.SignalWidth = StartOptions.Options.SignalWidth;
            SignalsViewPanel.TimeInterval = StartOptions.Options.TimeInterval;
            SignalsViewPanel.TimeTableVisible = StartOptions.Options.ViewGrid;
            SignalsViewPanel.TimeTagsVisible = StartOptions.Options.ViewTime;
            //заполнить начальные значения для элементов управления диаграммы
            SignalScaleWidth.Value = StartOptions.Options.SignalWidth;
            TimeSpanBox.Value = StartOptions.Options.TimeInterval;
            TimeTableCheckBox.Checked = StartOptions.Options.ViewGrid;
            TimeTagsCheckBox.Checked = StartOptions.Options.ViewGrid;
            //блокировка настроек
            this.OptionsGroup.Enabled = false;
            _Manager.Emulate();
        }

        private void OptionsGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            _Manager.TactCount = StartOptions.Options.TactCount;
            _Manager.TicPerTact = StartOptions.Options.TactTime;
            _Manager.InitialSignal = StartOptions.Options.StartSignal;
        }

        private void сохранитьИзображениеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SavePictDialog.ShowDialog() == DialogResult.OK)
            {
                SignalsViewPanel.SaveToImage(SavePictDialog.FileName);
            }
        }

        #endregion
    }
}